package com.yawn.zerodefect.controller.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @author Created by yawn on 2018-01-26 11:16
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${zd.access-uris}")
    private String accessUris;

    private List<String> uriList;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (uriList == null) {
            uriList = Arrays.asList(accessUris.split(","));
        }
        if (!uriList.contains(requestURI)) {
            HttpSession httpSession = request.getSession();
            Object isLogin = httpSession.getAttribute("isLogin");
            if (isLogin == null) {
                response.sendRedirect("/default");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 不用实现
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 不用实现
    }
}
